package com.itheima.factory;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 包名:com.itheima.factory
 * @author Leevi
 * 日期2020-08-09  09:18
 */
public class BeanFactory {
    private static Map<String,Object> map = new HashMap();
    static {
        try {
            //将读取配置文件的代码，放到静态代码块中
            //解析配置文件beans.xml,根据id的值，获取class的值
            SAXReader saxReader = new SAXReader();
            InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
            Document document = saxReader.read(is);
            //获取所有的bean标签
            List<Element> elementList = document.selectNodes("//bean");
            if (elementList != null) {
                for (Element element : elementList) {
                    //获取标签的id属性
                    String idAttr = element.attributeValue("id");
                    String className = element.attributeValue("class");
                    //根据类的全限定名，创建出该类的对象
                    Object obj = Class.forName(className).newInstance();
                    //以id作为key，以对象作为value存入map中
                    map.put(idAttr,obj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Object getBean(String id){
        try {
            //根据传入的id，获取到对应的className
            Object obj = map.get(id);
            if (obj != null) {
                return obj;
            }
            throw new RuntimeException("找不到对应的类!!!");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
